import request, { cacheRequest } from '@/utils/request';
import { HttpCode } from '@/utils/contacts';

// 获取数据权限
export async function queryDataPower(params) {
  return request(`/power/dataPower/common/${params}`);
}

// 获取菜单权限
export async function queryMenuPower(params) {
  return request('/power/menu/menus', {
    method: 'POST',
    data: params,
  });
}

/**
 * 应用管理
 * @returns
 */

// 新建应用
export async function addApplication(data) {
  return request('/power/custom/application/add', {
    method: 'POST',
    data,
  });
}

// 编辑应用
export async function updateApplication(data) {
  return request('/power/custom/application/update', {
    method: 'POST',
    data,
  });
}

// 菜单图标库查询
export async function getMenuIconList() {
  return request('/power/custom/application/getMenuIconList', {
    method: 'GET',
  });
}

// 角色查询
export async function getRoleList() {
  const res = await request('/power/custom/role/list', {
    method: 'GET',
  });
  if (res && res.statusCode === HttpCode.SUCCESS) {
    const arr = res.data.reduce((_t, _v) => {
      return [..._t, { ..._v, id: _v.roleId, name: _v.roleName }];
    }, []);
    res.data = arr;
  }
  return res;
}

// 二级菜单查询
export async function getSecondMenuList() {
  const res = await request('/power/custom/secondMenu/list', {
    method: 'GET',
  });
  if (res && res.statusCode === HttpCode.SUCCESS) {
    const arr = res.data.reduce((_t, _v) => {
      return [..._t, { ..._v, id: _v.mappingMenuId, name: _v.secondMenuName }];
    }, []);
    res.data = arr;
  }
  return res;
}

// 应用列表高级查询
export async function getApplicationList(data) {
  return request('/power/custom/application/list', {
    method: 'post',
    data,
  });
}

// 删除应用
export async function delApplication(id) {
  return request(`/power/custom/application/del?customApplicationId=${id}`, {
    method: 'GET',
  });
}

// 编辑操作---全量查询
export async function getApplicationAllInfo(id) {
  const res = await request(`/power/custom/getApplicationAllInfo?customApplicationId=${id}`, {
    method: 'GET',
  });
  if (res && res.statusCode === HttpCode.SUCCESS) {
    const _menuArr = res.data.firstMenuList.map((_m) => {
      _m.operationType = 2;
      const _secList = _m.secondMenuList.reduce((_t, _v) => {
        if (_v.selected) {
          _v.operationType = 2; // 2 修改
          _v.name = _v.secondMenuName;
          _v.id = _v.mappingMenuId;
          if (_v.homePageFlag) {
            _v.homePageFlag = true;
          } else {
            _v.homePageFlag = false;
          }
          return [..._t, _v];
        } else {
          return _t;
        }
      }, []);
      const sortSec = _.orderBy(_secList, ['sort'], ['asc']);
      _m.secondMenuList = sortSec;
      return _m;
    });
    const sortMenu = _.orderBy(_menuArr, ['sort'], ['asc']);
    const _roleArr = res.data.roleList.reduce((_t, _v) => {
      if (_v.selected) {
        _v.name = _v.roleName;
        _v.id = _v.roleId;
        return [..._t, _v];
      } else {
        return _t;
      }
    }, []);
    res.data.roleList = _roleArr;
    res.data.firstMenuList = sortMenu;
  }
  return res;
}

function handleApplications(
  menuList = [],
  pIndex = 0,
  menuObj = {},
  parentId = '',
  parentPath = '',
  buttonPermissions = [],
  customApplicationId = '',
  customApplicationName = '',
  firstMenuId = '',
) {
  //第一层是应用，第二层是一级菜单，第三层才是子菜单
  const isChildren = pIndex > 1;
  const children = menuList.map((item) => {
    const curId =
      item.customApplicationId || item.firstMenuId || item.secondMenuId || item.menuCode;
    const curPath = item.name ? `${parentPath}${parentPath ? '/' : ''}${item.name}` : '';
    const key = `${parentId}${parentId ? '-' : ''}${curId}`;
    if (item.buttons?.length) {
      // eslint-disable-next-line
      buttonPermissions = item.buttons.reduce((p, c) => [...p, { menuCode: c }], [
        ...buttonPermissions,
      ]);
    }
    if (item.children?.length) {
      const { array, buttonPermissions: btns } = handleApplications(
        item.children,
        pIndex + 1,
        menuObj,
        key,
        curPath,
        buttonPermissions,
        item.customApplicationId || customApplicationId,
        item.customApplicationName || customApplicationName,
        item.firstMenuId || firstMenuId,
      );
      item.children = array;
      // eslint-disable-next-line
      buttonPermissions = btns;
    }
    //第一层有应用id，传递到下边给其他菜单赋值应用id
    if (!item.customApplicationId) {
      item.customApplicationId = customApplicationId;
      item.customApplicationName = customApplicationName;
    }
    if (!item.firstMenuId) {
      item.firstMenuId = firstMenuId;
    }
    item.curPath = curPath;
    //调用visitRecord时之前是用的secondMenuId，现在改成menuId
    item.secondMenuId = item.menuId;
    item.nmae = item.customApplicationName;
    //这里不知道是干啥的，原来的逻辑先这样了
    // url 相当于后台菜单配置的component 如果不想展示则不需要配置
    item.component = isChildren ? item.url : item.customApplicationId;
    item.path = isChildren ? `/${item.url}` : `/${item.name}-${curId}`;
    item.isChildren = isChildren;
    item.key = key;
    //firstMenuId和parentKeys不知道什么作用，暂未赋值

    if (item.isEAM) {
      item.isEam = true;
      const path = `Eam/SubMenu/${item.menuCode}`;
      item.url = path;
      item.component = path;
      item.path = `/${path}`;
    }

    if (item.path.indexOf('/ShanXi') >= 0 && !item.isEAM) {
      if (!['/ShanXiMenuConfig', '/ShanXiAddTable', '/ShanXiDeptConfig'].includes(item.path)) {
        const path = `DynamicPage/${item.menuCode}`;
        item.url = path;
        item.component = path;
        item.path = `/${path}`;
      }
    }
    if (pIndex == 0) {
      menuObj[item.customApplicationId] = item;
    }
    return item;
  });

  return { array: children, buttonPermissions, menuObj };
}

// 获取应用列表
export function queryMenuPowerNew(data = {}) {
  return new Promise(async (resolve) => {
    let res = await request('/power/custom/applications', { method: 'post', data });
    if (res?.statusCode == HttpCode.SUCCESS) {
      const { array, buttonPermissions, menuObj } = handleApplications(res?.data);
      res.data = array;
      res.buttonPermissions = buttonPermissions;
      res.menuObj = menuObj;
    } else {
      res = {};
      res.data = [];
      res.menuObj = {};
      res.buttonPermissions = [];
    }
    resolve(res);
  });
}

/**
 * 租户应用打开时间记录
 * @returns
 */
export async function visitRecord(data) {
  return request(`/power/custom/application/visitRecord`, {
    method: 'post',
    data,
  });
}

/**
 * 租户应用最后打开查询
 * @returns
 */
export async function getLastVisit() {
  return request(`/power/custom/application/getLastVisit`, {
    method: 'get',
  });
}

// 保存logo图片
export async function saveLogo(data) {
  return request(`/power/logo/saveLogo`, {
    method: 'post',
    data,
    processData: true,
  });
}

// 设置回默认logo
export async function setDefultLogo() {
  return request(`/power/logo/setDefultLogo`, {
    method: 'post',
  });
}

// 获取logo地址
export async function getLogo() {
  let logoUrl = '';
  const file = await request(`/power/logo/getLogo`, {
    method: 'GET',
  });
  const fileId = file?.data?.fileId ?? '';
  if (fileId) {
    const res = await downLoadFiles({ fileId });
    logoUrl = res ? URL.createObjectURL(new Blob([res])) : '';
  }
  return Promise.resolve({ logoUrl, statusCode: HttpCode.SUCCESS });
}

export async function downLoadFiles(data) {
  return request(`/annex/annex/downLoadFiles`, {
    method: 'post',
    data,
    responseType: 'blob',
    headers: {
      Accept: 'text/html, application/xhtml+xml, */*',
    },
  });
}
